package com.liuyu.common.framework.validator.impl;

import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.liuyu.common.framework.validator.annotation.ValidExtendService;
import com.liuyu.common.framework.validator.annotation.ValidOrderCmd;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

/**
 * @author LiuYu
 * @Project:eplatform
 * @ClassName:InsuredRequestValidator
 * @Description:${todo}
 * @date 2019/5/710:49
 * @Copyright:liuyu
 * @version:V1.0
 */
@Slf4j
public class ValidOrderCmdValidator implements ConstraintValidator<ValidOrderCmd, Object> {

    public static final String SUFFIX = "0000";

    private static final Gson GSON = new Gson();


    @Autowired
    private MessageSource messageSource;

    @Autowired(required = false)
    private ValidExtendService validExtendService;


    @Override
    public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
        log.info("正在进行数据验证");
        List<String> errorList = Lists.newArrayListWithCapacity(50);
        if (validExtendService != null) {
            validExtendService.isValidWithoutAuth(o, errorList);
        }
        clearNull(errorList);
        Iterator it = errorList.iterator();
        while (it.hasNext()) {
            String error = (String) it.next();
            constraintValidatorContext.buildConstraintViolationWithTemplate(error).addConstraintViolation();
        }
        return errorList.isEmpty();
    }

    /**
     * 清理空值
     *
     * @param list
     * @param <T>
     */
    public static <T> void clearNull(List<T> list) {
        Collection nuCon = new Vector();
        nuCon.add(null);
        list.removeAll(nuCon);
    }


    /**
     * 清理list中的null值
     *
     * @param oldList
     * @param <T>
     * @return
     */
    public static <T> List<T> removeNull(List<? extends T> oldList) {
        oldList.removeAll(Collections.singleton(null));
        return (List<T>) oldList;
    }


}
